package cn.player.adapter;

import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import java.util.List;

import cn.player.App;
import cn.player.R;
import cn.player.act.ChannelListActivity;
import cn.player.entity.ChannelInfo;
import cn.player.view.SlideView;
import cntv.player.core.util.ToastUtil;
import cntv.player.core.util.Utils;
import cntv.player.engine.Const;
import cn.player.media.util.DateUtil;

/**
 * 频道信息列表adpater
 *
 * @author zengliang
 */
public class ChannelInfoAdapter extends BaseAdapter {

    private App app;
    private FinalBitmap finalBitamp;
    private FinalHttp finalHttp;
    private int lastPosition;
    private ChannelListActivity mChannelListActivity;
    private List<ChannelInfo> mData;
    private int layoutResource;
    private ViewHolder viewHolder;


    public ChannelInfoAdapter(ChannelListActivity mContext, List<ChannelInfo> mData, int layoutResource) {
        // TODO Auto-generated constructor stub
        app = (App) mContext.getApplicationContext();
        finalBitamp = app.getFinalBitmap();
        finalHttp = app.getFinalHttp();
        this.mChannelListActivity = mContext;
        this.mData = mData;
        this.layoutResource = layoutResource;
    }

    public void setData(List<ChannelInfo> mData) {
        this.mData = mData;
    }

/*	@Override
	protected void addViewId() {
		// TODO Auto-generated method stub
		mViewIds.add(R.id.iv_channel_image);
		mViewIds.add(R.id.iv_channel_icon);
		mViewIds.add(R.id.tv_channel_name);
		mViewIds.add(R.id.tv_channel_live_title);
		mViewIds.add(R.id.pb_live_run_progress);
	}*/
	
/*	@Override
	protected void animationShow(int position,View convertView) {
		// TODO Auto-generated method stub
		super.animationShow(position,convertView);
		
		Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
		convertView.startAnimation(animation);
	    lastPosition = position;
		
	}*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
//		View view = super.getView(position, convertView, parent);
//	    view.setTag(getItemId(position));
        SlideView slideView = (SlideView) convertView;
        if (slideView == null) {
            View itemView = View.inflate(mChannelListActivity, layoutResource, null);
            slideView = new SlideView(mChannelListActivity);
            slideView.setContentView(itemView);

            viewHolder = new ViewHolder();
            viewHolder.slideView = slideView;
            viewHolder.deleteView = (ViewGroup) slideView.findViewById(R.id.holder);
            viewHolder.iv_channel_img = (ImageView) slideView.findViewById(R.id.iv_channel_image);
            viewHolder.iv_channel_icon = (ImageView) slideView.findViewById(R.id.iv_channel_icon);
            viewHolder.tv_channel_name = (TextView) slideView.findViewById(R.id.tv_channel_name);
            viewHolder.tv_channel_live_title = (TextView) slideView.findViewById(R.id.tv_channel_live_title);
            viewHolder.pb_live = (ProgressBar) slideView.findViewById(R.id.pb_live_run_progress);

            slideView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) slideView.getTag();
        }

        viewHolder.slideView.shrink();

        final int fPosition = position;
        viewHolder.slideView.setOnSlideListener(mChannelListActivity);
        viewHolder.deleteView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String channelTitle = mData.get(fPosition).getTitle();
                mData.remove(fPosition);
                notifyDataSetChanged();
                ToastUtil.showToast(mChannelListActivity, "删除《" + channelTitle + "》频道", ToastUtil.LENGTH_SHORT);
            }
        });


        ChannelInfo info = mData.get(position);
        if (Utils.strToLong(info.getAutoImg()) == 1) {
            String autoImgUrl = app.getBaseUrls().get(Const.KEY_AUTOIMG_URL).getUrl() + info.getChannelId() + "_01.png" + "?rdm=null";
            finalBitamp.display(viewHolder.iv_channel_img, autoImgUrl);
        } else {
            finalBitamp.display(viewHolder.iv_channel_img, info.getImgUrl());
        }
        finalBitamp.display(viewHolder.iv_channel_icon, info.getChannelImg());
        viewHolder.tv_channel_name.setText(info.getTitle());
        if (info.isReady()) {
            viewHolder.tv_channel_live_title.setText(info.getPlayTitle());
            viewHolder.pb_live.setProgress(info.getPlayProgress());
            setPropertyAnimation(position, viewHolder.pb_live, info.getPlayProgress());
        } else {
            getChannelPlayLiveInfo(viewHolder.tv_channel_live_title, viewHolder.pb_live, position);
        }
		
		
		/*Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
		convertView.startAnimation(animation);
	    lastPosition = position;*/


        return slideView;
    }

/*	@Override
	protected void updateItemViews(int position) {
		// TODO Auto-generated method stub
		ImageView iv_channel_img = (ImageView) viewHolder.getView(R.id.iv_channel_image);
		ImageView iv_channel_icon = (ImageView) viewHolder.getView(R.id.iv_channel_icon);
		TextView tv_channel_name = (TextView) viewHolder.getView(R.id.tv_channel_name);
		TextView tv_channel_live_title = (TextView) viewHolder.getView(R.id.tv_channel_live_title);
		ProgressBar pb_live = (ProgressBar) viewHolder.getView(R.id.pb_live_run_progress);
		
		ChannelInfo info = mData.get(position);
		if(Utils.strToLong(info.getAutoImg()) == 1){
			String autoImgUrl = app.getBaseUrls().get(Const.KEY_AUTOIMG_URL).getUrl() + info.getChannelId() + "_01.png" + "?rdm=null";
			finalBitamp.display(iv_channel_img, autoImgUrl);
		}else{
			finalBitamp.display(iv_channel_img, info.getImgUrl());
		}
		finalBitamp.display(iv_channel_icon, info.getChannelImg());
		tv_channel_name.setText(info.getTitle());
		if(info.isReady()){
			tv_channel_live_title.setText(info.getPlayTitle());
			pb_live.setProgress(info.getPlayProgress());
//			setPropertyAnimation(position,pb_live, info.getPlayProgress());
		}else{
//			getChannelPlayLiveInfo(position);
		}
		
	}*/

    /**
     * 获取频道正在直播的相关信息并更新列表
     *
     * @param position
     * @param tvPlay
     * @param pbProgressBar
     */
    private void getChannelPlayLiveInfo(final TextView tvPlay, final ProgressBar pbProgressBar, final int position) {
        if (mData == null || mData.get(position) == null) {
            return;
        }
        String infoUrl = app.getBaseUrls().get(Const.KEY_LIVING_URL).getUrl() + "&c=" + mData.get(position).getChannelId();
        finalHttp.get(infoUrl, new AjaxCallBack<String>() {

            @Override
            public void onStart() {
                // TODO Auto-generated method stub
                super.onStart();
            }

            @Override
            public void onSuccess(String result) {
                // TODO Auto-generated method stub
                super.onSuccess(result);
                try {
                    JSONObject data = new JSONObject(result);

                    long currentTime = System.currentTimeMillis();
                    String sStaTime = DateUtil.getTimeString(currentTime) + " " + data.optString("s").trim();//组装成 yyyyMMdd HH:mm:ss 格式日期
                    String sEndTime = DateUtil.getTimeString(currentTime) + " " + data.optString("e").trim();//组装成 yyyyMMdd HH:mm:ss 格式日期
                    long startTime = DateUtil.getMilliseconds(sStaTime, Const.DATE_TYPE_YMDHMS);
                    long endTime = DateUtil.getMilliseconds(sEndTime, Const.DATE_TYPE_YMDHMS);
                    int progress;
                    if (currentTime <= startTime) {
                        progress = 0;
                    } else if (currentTime >= endTime) {
                        progress = 100;
                    } else {
                        progress = (int) ((float) (currentTime - startTime) / (endTime - startTime) * 100);
                    }
                    tvPlay.setText(data.optString("t"));
                    setPropertyAnimation(position, pbProgressBar, progress);

                    mData.get(position).setPlayTitle(data.optString("t"));
                    mData.get(position).setPlayProgress(progress);
                    mData.get(position).setReady(true);
					
					
					
					/*View convertView = viewHolder.getConvertView();
					if((Long)convertView.getTag() == position){
						
						TextView tvPlay = (TextView) convertView.findViewById(R.id.tv_channel_live_title);
						ProgressBar pb_live = (ProgressBar) convertView.findViewById(R.id.pb_live_run_progress);
						pb_live.setProgress(progress);
					}*/

//					notifyDataSetChanged();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                // TODO Auto-generated method stub
                super.onFailure(t, errorNo, strMsg);
            }

        });
    }

    @SuppressLint("NewApi")
    private void setPropertyAnimation(final int position, final ProgressBar progressBar, final int progress) {
        if (android.os.Build.VERSION.SDK_INT >= 11 && !mData.get(position).isAnim() && progress != 0) {
            ValueAnimator anim = ObjectAnimator.ofInt(0, progress);
            anim.setDuration(1000);
            anim.addUpdateListener(new AnimatorUpdateListener() {

                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    progressBar.setProgress((Integer) animation.getAnimatedValue());
                    if ((Integer) animation.getAnimatedValue() == progress) {
                        mData.get(position).setAnim(true);
                    }
                }
            });
            anim.setEvaluator(new IntEvaluator());
            anim.start();
        } else {
            progressBar.setProgress(progress);
        }
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return mData != null ? mData.size() : 0;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return mData != null ? mData.get(position) : position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public class ViewHolder {
        public ImageView iv_channel_img;
        public ImageView iv_channel_icon;
        public TextView tv_channel_name;
        public TextView tv_channel_live_title;
        public ProgressBar pb_live;
        public SlideView slideView;
        public ViewGroup deleteView;
    }


}
